<?php

namespace Modules\Admin\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Admin\Http\Requests\RoleRequest;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
        $roles = Role::where('name','!=',config('hd_module.webmaster'))->get();
        return view('admin::role.index',compact('roles'));
    }


    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(RoleRequest $request)
    {

        Role::create(['name'=>$request->name,'title'=>$request->title]);
        session()->flash('success','角色添加成功');
        return back();
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show()
    {
        return view('admin::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit()
    {
        return view('admin::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(RoleRequest $request,$id)
    {
        $role = Role::find($id);
        $role->update(['name'=>$request->name,'title'=>$request->title]);
       session()->flash('success','编辑成功');
        return back();

    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
        //删除方法1:
        Role::destroy($id);
        //删除方法2:
        //找到对应id的用户数据
//        $admin = Admin::find($id);
//        $admin->delete();
        //设置闪存并返回

        return ['valid'=>1,'message'=>'删除成功'];
    }
    /**
     * 分配权限
     */
    public function permission(Role $role){
        //获取所有模块的权限数据
        $modules = \HDModule::getPermissionByGuard('admin');
//        dump($modules);
        return view('admin::role.permission',compact('role','modules'));
    }

    /**
     * 添加权限
     */
    public function permissionStore(Request $request,Role $role){
//        dd($request->all());
        if(!$request->name){
            session()->flash('danger','最少选择一个权限,或者返回不设置');
            return back();
        }
        $role->syncPermissions($request->name);
        session()->flash('success','权限设置成功');
        return back();
    }
}
